package swu.cx.myglidetest

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Handler
import android.os.Looper
import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.BlockingDeque
import java.util.concurrent.BlockingQueue

class BitmapDispatcher(val requestQueue:BlockingQueue<BitmapRequest>): Thread() {
    val handler = Handler(Looper.getMainLooper())
    override fun run() {
        while (!isInterrupted){
            //从队列中获取请求
            val request = requestQueue.take()
            //设置占位图片
            showloadingImage(request)
            //下载图片
            val bitmap = downloadBitmap(request)
            //展示图片
            showBitmap(bitmap,request)
        }
    }
    fun showBitmap(bitmap: Bitmap,request: BitmapRequest){
        if (request.img!=null && bitmap!=null && request.img.get()!!.tag == request.urlMd5){
            handler.post {
                request.img.get()?.setImageBitmap(bitmap)
            }
        }
    }
    fun showloadingImage(request: BitmapRequest){
        if (request.loadingResId>0){
            val imageView = request.img.get()
            handler.post{
                imageView?.setImageResource(request.loadingResId)
            }
        }
    }

    fun downloadBitmap(request: BitmapRequest):Bitmap{
        val url = URL(request.url)
        val conn = url.openConnection() as HttpURLConnection
        return BitmapFactory.decodeStream(conn.inputStream).also {
            conn.disconnect()
        }
    }
}